<?php
namespace App\Http\Controllers\Company;

use App\Exceptions\ApiException;
use App\Http\Requests\BasicRequest;
use App\Http\Requests\ManageWorkCreateRequest;
use App\Mail\Basic;
use App\Models\ClientUser;
use App\Models\ClientUserRongcloud;
use App\Models\ManageWork;
use App\Models\ManageWorkConfirm;
use App\Models\ManageWorkImage;
use App\Models\ManageWorkType;
use App\Models\Message;
use App\Models\ServiceTeamDetail;
use Illuminate\Support\Facades\DB;

class ManageWorkController extends CommonController {
    public function list(BasicRequest $request){
        $keyword = $request->input('keyword');
        $type = $request->input('type',1);
        $list = ManageWork::select('manage_work.id','manage_work.type','manage_work.start_time','manage_work.status','manage_work.end_time','manage_work.uid','manage_work.manage_uid')
            ->when($type,function($query) use($type){
                if($type==1) {
                    $query->where('manage_work.uid',$this->uid);
                }else if($type==2){
                    $query->leftJoin('manage_work_confirm','manage_work_confirm.work_id','=','manage_work.id')
                        ->where('manage_work.manage_uid',$this->uid)
                        ->orWhere(function($query){
                            $query->where(['manage_work_confirm.manage_id'=>$this->uid,'manage_work_confirm.status'=>5]);
                        });
                }
            })->when($keyword,function($query) use($keyword){
                $query->leftJoin('client_user','client_user.id','=','manage_work.uid')
                    ->leftJoin('manage_work_type','manage_work_type.id','=','manage_work.type')
                    ->where('client_user.realname','like','%'.$keyword.'%')
                    ->orWhere('manage_work_type.name','like','%'.$keyword.'%');
            })->pages()->each(function($v,$k){
                $v->uname = ClientUser::where('id',$v->uid)->value('realname');
                $v->manage_name = ClientUser::where('id',$v->manage_uid)->value('realname');
                $v->type_name = ManageWorkType::where('id',$v->type)->value('name');
                $v->title = $v->uname.'的'.$v->type_name;
                $v->status_name = ManageWork::getStatusName($v->status,$v->manage_name);
                $v->avatar = ClientUser::where('id',$v->uid)->value('avatar');
            });
        return json_success('OK',$list);
    }

    /**
     * @param BasicRequest $request
     * @return array
     * 工单详情
     */
    public function detail(BasicRequest $request){
        $id = $request->input('id');
        $v = ManageWork::find($id);
        $v->uname = ClientUser::where('id',$v->uid)->value('realname');
        $v->manage_name = ClientUser::where('id',$v->manage_uid)->value('realname');
        $v->type_name = ManageWorkType::where('id',$v->type)->value('name');
        $v->title = $v->uname.'的'.$v->type_name;
        $v->status_name = ManageWork::getStatusName($v->status,$v->manage_name);
        $v->image = ManageWorkImage::where(['work_id'=>$id,'type'=>1])->get();
        $v->team_name = ServiceTeam::where(['id'=>$v->manage_team_id])->value('name')?:'物业';
        $v->confirm  = ManageWorkConfirm::where('work_id',$id)->select('manage_uid','status','created_at')->get()->each(function($val,$kal) use($id){
            $val->manage_name =  ClientUser::where('id',$val->manage_uid)->value('realname');
            $val->team_name = ServiceTeamDetail::where(['uid'=>$val->manage_uid])->value('name')?:$val->manage_name;
            $val->status_name = ManageWork::getStatusName($val->status,$val->manage_name);
            $val->image = ManageWorkImage::where(['work_id'=>$id,'uid'=>$val->manage_uid,'type'=>2])->get();
        });
        return json_success('OK',$v);
    }
    /**
     * @param BasicRequest $request
     * @return array
     * 创建工单
     */
    public function create(BasicRequest $request){
        $manage_uid = $request->input('manage_id');
        $type = $request->input('type');
        $img = $request->input('img');
        $content = $request->input('content');
        $start_time = $request->input('start_time');
        $end_time = $request->input('end_time');
        $message_ids = $request->input('message_ids');
        $input = array(
            'village_id'=>$this->ship->village_id,
            'uid'=>$this->uid,
            'team_id'=>ServiceTeamDetail::where(['uid'=>$this->uid])->value('team_id')?:0,
            'content'=>$content,
            'message_ids'=>$message_ids,
            'manage_uid'=>$manage_uid,
            'manage_team_id'=>ServiceTeamDetail::where(['uid'=>$manage_uid])->value('team_id')?:0,
            'type'=>$type,
            'status'=>1,
            'start_time'=>$start_time,
            'end_time'=>$end_time,
        );
        $work_id = DB::transaction(function() use($input,$img){
            $work_id = ManageWork::create($input)->id;
            if($img) {
                $imgs = explode(',',$img);
                foreach ($imgs as $key=>$val){
                    ManageWorkImage::created($work_id,$this->uid,$val,1);
                }
            }
            $type_name = ManageWorkType::where('id',$input['type'])->value('name');
            $content = $this->user->realname.'的'.$type_name;
            Message::message_push($input['manage_uid'],'manage_work',$content,$work_id);
            return $work_id;
        });
        return json_success('OK',['id'=>$work_id]);
    }

    /**
     * @param BasicRequest $request
     * @return array
     * 获取工单类型
     */
    public function type(BasicRequest $request){
        $return = ManageWorkType::get();
        return json_success('OK',$return);
    }

    /**
     * @param BasicRequest $request
     * @return array
     * 管理人员融云聊天记录与未读列表
     */
    public function rongcloud(BasicRequest $request)
    {
        $message_ids = $request->input('message_ids');
        $ids=null;
        if($message_ids) {
            $ids = explode(',',$message_ids);
        }
        $data = ClientUserRongcloud::select(DB::raw('client_user_rongcloud.id,house.house_sn as house_long,from_uid,to_uid,u.avatar,house.house_sn as username,mobile,client_user_rongcloud.created_at,client_user_rongcloud.type,content,h.house_id'))
            ->leftJoin('client_user as u', 'u.id', '=', 'client_user_rongcloud.from_uid')
            ->orderBy('client_user_rongcloud.id', 'desc')
            ->when($ids,function($query) use($ids){
                $query->whereIn('client_user_rongcloud.id',$ids);
            })
            ->pages()
            ->each(function ($v, $k) {
                if ($v->type == 'RC:TxtMsg') {
                    $v->content = str_limit(json_decode($v->content)->content, 10);
                } else {
                    $v->content = '[不支持预览]';
                }
            });
        return json_success('OK', $data);
    }

    /**
     * @param ManageWorkCreateRequest $request
     * @return array
     * @throws \Exception
     * @throws \Throwable
     * 处理工单
     */
    public function confirm(ManageWorkCreateRequest $request){
        $id = $request->input('id');
        $status = $request->input('status');
        $remark = $request->input('remark');
        $image = $request->input('image');
        $manage_uid = $request->input('manage_uid');

        DB::transaction(function($v,$k) use($id,$status,$remark,$image,$manage_uid){
            $manage_work = ManageWork::find($id);
            if($manage_work->manage_uid!=$this->uid){
                throw new \Exception('您不是该工单的当前审批人');
            }
            if($manage_work->status!=1||$manage_work->status!=5){
                throw new \Exception('该工单已结束，无法操作');
            }
            if($status==5){
                if(!$manage_uid){
                    throw new \Exception('请选择流转人');
                }else{
                    $manage_team_id = ServiceTeamDetail::where(['uid'=>$manage_uid])->value('team_id')?:0;
                    ManageWork::where('id',$id)->update(['status'=>5,'manage_uid'=>$manage_uid,'manage_team_id'=>$manage_team_id]);
                }
            }else {
                ManageWork::where('id', $id)->update(['status'=>$status]);
            }
            $confirm = array(
                'work_id'=>$id,
                'status'=>$status,
                'uid'=>$manage_work->uid,
                'manage_uid'=>$this->uid,
                'remark'=>$remark
            );
            ManageWorkConfirm::create($confirm);

            if($image) {
                $imgs = explode(',',$image);


                foreach ($imgs as $key=>$val){
                    ManageWorkImage::created($id,$this->uid,$val,2);
                }
            }
            $content = ManageWork::getStatusName($status,$this->user->realname);
            Message::message_push($manage_work->uid,'manage_work_confirm',$content,$id);
        });
        return json_success('OK');
    }
}